'''
Created on Dec 5, 2010

@author: jackreilly
'''

from google.appengine.ext import db
from jettube.models import getFromJetKey, User
from jettube.models.User import getUserFromRequest

LIKE_KEY = 'like'
USER_KEY = 'opinionuser'
SONG_ID_KEY = 'songid'

NOPINIONS = 10


class Opinion( db.Model ):
    like = db.BooleanProperty()
    user = db.ReferenceProperty( User.User )
    songid = db.StringProperty()
    
def newOpinionFromRequest(request):
    user = getUserFromRequest(request)
    if not user:
        return
    song_id = getFromJetKey(request, SONG_ID_KEY)
    opinion = Opinion.get_or_insert(generateKeyFromUserSongId(user,song_id))
    opinion.user = user
    opinion.songid = song_id
    like = getFromJetKey(request, LIKE_KEY)
    if like == 'true':
        like = True
    else:
        like = False
    opinion.like = like
    opinion.put()
                
    return opinion
    
    
def generateKeyFromUserSongId(user,song_id):
    return '%s ::: %s' % (user.key(), song_id)

def getOpinionsFromRequest(request):
    songid = getFromJetKey(request, SONG_ID_KEY)
    if not songid:
        return False
    return Opinion.all().filter('songid',songid).fetch(NOPINIONS)

def getOpinionsFromSongId(songid):
    if not songid:
        return False
    return Opinion.all().filter('songid',songid).fetch(NOPINIONS)

def getOpinionsDictionaryFromOpinions(opinions):
    return [{LIKE_KEY:opinion.like, 
             User.NAME_KEY:opinion.user.name, 
             User.PIC_KEY:opinion.user.picUrl} for opinion in opinions]

def getOpinionsDictionaryFromRequest(request ):
    opinions = getOpinionsFromSongId(getFromJetKey(request, SONG_ID_KEY))
    return getOpinionsDictionaryFromOpinions(opinions)
    
def getOpinionsDictionaryFromSongId(songid ):
    return getOpinionsDictionaryFromOpinions(getOpinionsFromSongId(songid))
    
